﻿using System;

using agsXMPP;
using agsXMPP.protocol.client;

using VSTalk.Model;

namespace VSTalk.Engine.Core.XmppConnection.PresenceListener
{
    internal class SingleClientPresenceListener : IPresenceListener
    {
        private readonly Client _client;

        private XmppClientConnection _connection;

        private static IConnectionManager ConnectionManager
        {
            get { return AppServices.Get<IConnectionManager>(); }
        }

        public SingleClientPresenceListener(Client client)
        {
            _client = client;
        }

        public void StartListen()
        {
            var clientConnection = ConnectionManager.GetOrCreateConnection(_client);
            _connection = clientConnection.Connection;
            _connection.OnPresence += InternalOnPresence;
        }

        private void InternalOnPresence(object sender, Presence pres)
        {
           OnPresenceReceived(_client, pres);
        }

        public void StopListen()
        {
            _connection.OnPresence -= InternalOnPresence;
        }

        public event Action<Client, Presence> PresenceReceived;
        protected virtual void OnPresenceReceived(Client arg1, Presence arg2)
        {
            var handler = PresenceReceived;
            if (handler != null) handler(arg1, arg2);
        }
    }
}